#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :overtime_statistics_page.py
# Time  :2025/4/11 9:44
# Email :fortunatedong@163.com
# Author:by Adonli
import os
import time

import pandas as pd
import streamlit as st
import toml
from config import ROOT_DIR

from st_aggrid import AgGrid, GridOptionsBuilder,GridUpdateMode
from utils.hr_task.overtime_statistics import OvertimeStatistics
from config import Header_space
Header_space()
# ding_hr_overtime_statistics_path = "C:/Users/yadong_li/Desktop/人事/20250410173800016.xlsx"
# ding_hr_department_path = "C:/Users/yadong_li/Desktop/人事/公司人员部门统计表.xlsx"
# ding_hr_overtime_statistics = pd.read_excel(ding_hr_overtime_statistics_path)
# ding_hr_department = pd.read_excel(ding_hr_department_path)
# data = pd.merge(left=ding_hr_overtime_statistics, right=ding_hr_department, how='left',left_on="加班人",right_on="姓名")
# hr_overtime_statistics_files = data[["审批记录(含处理人UserID)","加班类型","加班事由","加班人","开始时间","结束时间","加班时间","加班时长","时长","部门","组别"]]
# hr_overtime_statistics_files = hr_overtime_statistics_files.sort_values(["组别","加班人","开始时间"])
ding_current_hr_overtime_statistics_path = os.path.join(ROOT_DIR, 'Datas/hr_overtime_statistics_files/current_hr_overtime_statistics',)
hr_overtime_statistics_result_path = os.path.join(ROOT_DIR, 'Datas/hr_overtime_statistics_files/hr_overtime_statistics_result',)
configs_toml = os.path.join(ROOT_DIR, 'settings','configs.toml')

with open(configs_toml, "r", encoding="utf-8") as f:
    cfg = toml.load(f)
    hr_last_department_file_name = cfg['HRTASK']['HRLastDepartmentFileName']
with open(configs_toml, "r", encoding="utf-8") as f:
    cfg = toml.load(f)
    hr_overtime_statistics_name = cfg['HRTASK']['DingHRLastOvertimeStatisticsName']
st.subheader("人事部门加班统计", divider=True)

col1, col2 = st.columns([13,27])
with col1:
    department_uploaded_file = st.file_uploader(
            ":blossom:**部门成员如有改动，请上传新的部门架构文件:**", accept_multiple_files=False,
        )
    if department_uploaded_file is not None:
        bytes_data = department_uploaded_file.getvalue()
        cfg['HRTASK']['HRLastDepartmentFileName'] = department_uploaded_file.name
        with open(configs_toml, 'w', encoding="utf-8") as f:
            toml.dump(cfg, f)
        with open(f"{ding_current_hr_overtime_statistics_path}/{department_uploaded_file.name}", "wb") as f:
            f.write(bytes_data)

    st.write(":blossom:**当前员工所属部门表信息：**")
    department_df = pd.read_excel(f"{ding_current_hr_overtime_statistics_path}/{hr_last_department_file_name}")
    department_data = department_df[["部门","组别","姓名"]]
    # 配置AgGrid选项
    gb = GridOptionsBuilder.from_dataframe(department_data)
    gb.configure_default_column(groupable=True)
    gb.configure_grid_options(
        groupDefaultExpanded=False,  # 默认折叠所有分组
        autoGroupColumnDef={
            "headerName": "分组",
            "minWidth": 220,
            "cellRendererParams": {
                "suppressCount": False,
                "innerRenderer": "agGroupCellRenderer",
            },
        }
    )

    # 设置两列分组并隐藏原始列
    gb.configure_column("部门", rowGroup=True, hide=True)
    gb.configure_column("组别", rowGroup=True, hide=True)

    AgGrid(
        department_data,
        gridOptions=gb.build(),
        enable_enterprise_modules=True,
        update_mode='MODEL_CHANGED'
    )

with col2:
    overtime_statistics_uploaded_file = st.file_uploader(
        ":blossom:**请上传要统计的表格文件:**", accept_multiple_files=False,
    )
    if overtime_statistics_uploaded_file is not None:
        bytes_data = overtime_statistics_uploaded_file.getvalue()
        cfg['HRTASK']['DingHRLastOvertimeStatisticsName'] = overtime_statistics_uploaded_file.name

        with open(configs_toml, 'w', encoding="utf-8") as f:
            toml.dump(cfg, f)
        with open(f"{ding_current_hr_overtime_statistics_path}/{overtime_statistics_uploaded_file.name}", "wb") as f:
            f.write(bytes_data)
    col2_col1, col2_col2,col2_col3 = st.columns([1,1,1])
    with col2_col1:
        number = st.number_input(":blossom:**查询非本月数据，请输入数字：**",min_value=0,max_value=30,help="默认为0，统计本月加班数据；比如本月为4月，但要统计3月加班数据，则输入1（4-3）；本月为4月，但要统计2月加班数据，则输入2（4-2）")
        # st.write(number)
    with col2_col2:
        st.write("")
        st.write("")
        overtime_ststistics_button = st.button("开始执行统计",icon="😃",use_container_width = True)
    if overtime_ststistics_button:
        if overtime_statistics_uploaded_file is not None:
            hr_overtime_statistics_path = f"{hr_overtime_statistics_result_path}/结果统计{overtime_statistics_uploaded_file.name}"
            ding_hr_department_path =  f"{ding_current_hr_overtime_statistics_path}/{hr_last_department_file_name}"
            ding_hr_overtime_statistics_path = f"{ding_current_hr_overtime_statistics_path}/{overtime_statistics_uploaded_file.name}"
            OS = OvertimeStatistics(number,ding_hr_department_path,ding_hr_overtime_statistics_path,hr_overtime_statistics_path).load_hr_overtime_statistics()

            df = pd.read_excel(hr_overtime_statistics_path, engine='openpyxl')
            st.dataframe(df)
            cfg['HRTASK']['HROvertimeStatisticsPath'] = hr_overtime_statistics_path
            with open(configs_toml, 'w', encoding="utf-8") as f:
                toml.dump(cfg, f)
        else:
            st.error("先上传要统计的表格文件")
            OS = {"status":-1}
    with col2_col3:
        st.write("")
        st.write("")
        if overtime_ststistics_button:
            if OS["status"] == 0:
                hr_overtime_statistics_path = cfg['HRTASK']['HROvertimeStatisticsPath']
                with open(hr_overtime_statistics_path, "rb") as f:
                    st.download_button(
                        label="下载Excel文件",
                        data=f,
                        file_name=f"结果统计{overtime_statistics_uploaded_file.name}",
                        mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                    )